package main

import (
	"filetools/v2/pkg"
	"fmt"
	"io"
	"net"
	"os"
	"strconv"
	"strings"
	"time"
)

func main() {
	listen, err := net.Listen("tcp", ":3333")
	if err != nil {
		panic(err)
	}
	for {
		c, err := listen.Accept()
		if err != nil {
			panic(err)
		}
		// 启动连接线程
		go createClient(&Client{
			Conn: c,
			Data: []byte{},
		})
	}
}

type Client struct {
	net.Conn
	Data []byte
}

// 创建子线程读取数据
func createClient(client *Client) {
	defer client.Close()
	for {
		var bytes [128]byte
		i, err := client.Read(bytes[:])
		if err != nil {
			fmt.Println(err.Error())
			break
		} else {
			// 数据缓存
			client.Data = append(client.Data, bytes[0:i]...)
			client.onClientMessage()
		}
	}
}

func (client *Client) onClientMessage() {
	// 消息处理
	endString := string(client.Data[len(client.Data)-1])
	if strings.EqualFold(endString, "\b") {
		fileData := &pkg.FileData{}
		err := fileData.Parse(client.Data)
		if err != nil {
			fmt.Println("异常：", err.Error())
			client.Write([]byte(err.Error()))
			client.Close()
			return
		}
		version := 0
		versionFile := fileData.Name + "/version"
		file, err := os.Open(versionFile)
		if err == nil {
			versionData, _ := io.ReadAll(file)
			v, _ := strconv.Atoi(string(versionData))
			version = v
			file.Close()
		}
		version += 1
		// 日期
		day := time.Now().Format("2006-01-02")
		saveVersionPath := fileData.Name + "/" + day + "/" + fmt.Sprint(version)
		for _, f := range fileData.Files {
			// 开始本地存档
			fmt.Println("本地存档", f.Path)
			if strings.Index(f.Path, "/") == 0 {
				f.Path = f.Path[1:]
			}
			filePath := saveVersionPath + "/" + f.Path
			fileDir := filePath[0:strings.LastIndex(filePath, "/")]
			os.MkdirAll(fileDir, 0777)
			err := os.WriteFile(filePath, f.Bytes.Data, 0777)
			if err != nil {
				fmt.Println("写入失败：", err.Error())
			}
		}
		fmt.Println("更新版本：", version)
		werr := os.WriteFile(versionFile, []byte(fmt.Sprint(version)), 0777)
		if err != nil {
			fmt.Println(werr)
		}
		// 保存描述
		os.WriteFile(saveVersionPath+"/.log", []byte(fileData.Desc), 0777)
		client.Write([]byte("提交完成，当前版本：" + fmt.Sprint(version)))
		client.Close()
	}
}
